package com.mdd.admin.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.IOrderManageService;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.validate.order.OrderSearchValidate;
import com.mdd.admin.validate.order.OrderSendDeliveryValidate;
import com.mdd.admin.vo.order.OrderGoodsListVo;
import com.mdd.admin.vo.order.OrderInfoListVo;
import com.mdd.admin.vo.order.OrderLogListVo;
import com.mdd.admin.vo.order.OrderManageDetailVo;
import com.mdd.admin.vo.order.OrderManageListedVo;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.OrderUrgeMsg;
import com.mdd.common.entity.RefundLog;
import com.mdd.common.entity.RefundRecord;
import com.mdd.common.entity.Shop;
import com.mdd.common.entity.VipRecord;
import com.mdd.common.entity.delivery.ExpressCompany;
import com.mdd.common.entity.distribution.Distribution;
import com.mdd.common.entity.distribution.DistributionLevel;
import com.mdd.common.entity.distribution.DistributionOrder;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.goods.GoodsSku;
import com.mdd.common.entity.log.LogOrder;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.order.OrderAfter;
import com.mdd.common.entity.order.OrderAfterGoods;
import com.mdd.common.entity.order.OrderDelivery;
import com.mdd.common.entity.order.OrderGoods;
import com.mdd.common.entity.system.SystemAuthAdmin;
import com.mdd.common.entity.user.User;
import com.mdd.common.entity.user.UserAuth;
import com.mdd.common.enums.ClientEnum;
import com.mdd.common.enums.DeliverEnum;
import com.mdd.common.enums.DistributionEnum;
import com.mdd.common.enums.LogMoneyEnum;
import com.mdd.common.enums.LogOrderAfterEnum;
import com.mdd.common.enums.OrderAfterEnum;
import com.mdd.common.enums.OrderEnum;
import com.mdd.common.enums.OrderLogEnum;
import com.mdd.common.enums.PaymentEnum;
import com.mdd.common.enums.RefundEnum;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.LogIntegralMapper;
import com.mdd.common.mapper.OrderUrgeMsgMapper;
import com.mdd.common.mapper.RefundLogMapper;
import com.mdd.common.mapper.RefundRecordMapper;
import com.mdd.common.mapper.ShopMapper;
import com.mdd.common.mapper.VipRecordMapper;
import com.mdd.common.mapper.delivery.ExpressCompanyMapper;
import com.mdd.common.mapper.distribution.DistributionLevelMapper;
import com.mdd.common.mapper.distribution.DistributionMapper;
import com.mdd.common.mapper.distribution.DistributionOrderMapper;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.goods.GoodsSkuMapper;
import com.mdd.common.mapper.log.LogEarningsMapper;
import com.mdd.common.mapper.log.LogMoneyMapper;
import com.mdd.common.mapper.log.LogOrderAfterMapper;
import com.mdd.common.mapper.log.LogOrderMapper;
import com.mdd.common.mapper.order.OrderAfterGoodsMapper;
import com.mdd.common.mapper.order.OrderAfterMapper;
import com.mdd.common.mapper.order.OrderDeliveryMapper;
import com.mdd.common.mapper.order.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.system.SystemAuthAdminMapper;
import com.mdd.common.mapper.user.UserAuthMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.plugin.alipay.AliPayDriver;
import com.mdd.common.plugin.alipay.request.AliPayRefundRequest;
import com.mdd.common.plugin.delivery.DeliveryDriver;
import com.mdd.common.plugin.delivery.vo.KdQueryTrackParam;
import com.mdd.common.plugin.delivery.vo.KdTrackResultVo;
import com.mdd.common.plugin.notice.template.mnp.WeiXinApplication;
import com.mdd.common.plugin.wechat.WxPayDriver;
import com.mdd.common.plugin.wechat.request.RefundRequestV3;
import com.mdd.common.util.AmountUtil;
import com.mdd.common.util.ConfigUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.common.util.em.EMServiceUtil;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 订单服务实现类
 */
@Service
public class OrderManageServiceImpl implements IOrderManageService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    OrderGoodsMapper orderGoodsMapper;

    @Resource
    OrderDeliveryMapper orderDeliveryMapper;

    @Resource
    ExpressCompanyMapper expressCompanyMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    LogOrderMapper logOrderMapper;

    @Resource
    LogOrderAfterMapper logOrderAfterMapper;

    @Resource
    LogMoneyMapper logMoneyMapper;

    @Resource
    RefundRecordMapper refundRecordMapper;

    @Resource
    RefundLogMapper refundLogMapper;

    @Resource
    OrderAfterMapper orderAfterMapper;

    @Resource
    OrderAfterGoodsMapper orderAfterGoodsMapper;

    @Resource
    SystemAuthAdminMapper systemAuthAdminMapper;

    @Resource
    DistributionOrderMapper distributionOrderMapper;

    @Resource
    DataSourceTransactionManager transactionManager ;

    @Resource
    TransactionDefinition transactionDefinition;
    
    @Autowired
    private OrderUrgeMsgMapper orderUrgeMsgMapper;
    @Resource
    GoodsMapper goodsMapper;

    @Resource
    DistributionMapper distributionMapper;

    @Resource
    DistributionLevelMapper distributionLevelMapper;
    @Resource
    LogIntegralMapper logIntegralMapper;
    @Resource
    VipRecordMapper vipRecordMapper;
    @Resource
    LogEarningsMapper logEarningsMapper;
    @Resource
    EMServiceUtil eMServiceUtil;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    UserAuthMapper userAuthMapper;
    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    @Override
    public PageResult<OrderManageListedVo> list(PageValidate pageValidate, OrderSearchValidate orderSearchValidate) {
        Integer pageNo = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();

        MPJQueryWrapper<Order> orderMPJQueryWrapper = new MPJQueryWrapper<>();
        Integer searchType = orderSearchValidate.getSearchType();
        String searchKeyword = orderSearchValidate.getSearchKeyword();
        Integer userSearchType = orderSearchValidate.getUserSearchType();
        String searchUserKeyword = orderSearchValidate.getSearchUserKeyword();
        String searchTimeType = orderSearchValidate.getSearchTimeType();
        Integer startTime = orderSearchValidate.getStartTime();
        Integer endTime = orderSearchValidate.getEndTime();
        
        Integer shopId = LikeAdminThreadLocal.getShopId();
        if(null != shopId && shopId > 1) {
        	orderMPJQueryWrapper.eq("t.shop_id", shopId);
        }
        orderMPJQueryWrapper.eq("main_order", 1);
        // 订单搜索
        if(null != searchType && StringUtils.isNotEmpty(searchKeyword)){
            switch (searchType){
                case 1:
                    orderMPJQueryWrapper.like("t.order_sn","%"+searchKeyword+"%");
                    break;
                case 2:
                    orderMPJQueryWrapper.like("OG.goods_code","%"+searchKeyword+"%");
                    break;
                case 3:
                    orderMPJQueryWrapper.like("OG.goods_name","%"+searchKeyword+"%");
                    break;
            }
        }

        // 买家信息
        if(null != userSearchType && StringUtils.isNotEmpty(searchUserKeyword)){
            switch (userSearchType){
                case 1:
                    orderMPJQueryWrapper.like("U.sn","%"+searchUserKeyword+"%");
                    break;
                case 2:
                    orderMPJQueryWrapper.like("U.nickname","%"+searchUserKeyword+"%");
                    break;
                case 3:
                    orderMPJQueryWrapper.like("t.address_contact","%"+searchUserKeyword+"%");
                    break;
                case 4:
                    orderMPJQueryWrapper.like("t.address_mobile","%"+searchUserKeyword+"%");
                    break;
            }
        }

        // 时间搜索
        if(null != searchTimeType){
            String column = "t.create_time";
            if(searchTimeType.equals("pay")){
                column = "t.pay_time";
            }

            if(null != startTime){
                orderMPJQueryWrapper.ge(column, startTime);
            }

            if(null != endTime){
                orderMPJQueryWrapper.le(column, endTime);
            }
        }

        // 其它搜索
        orderMapper.setSearch(orderMPJQueryWrapper, orderSearchValidate, new String[]{
                "=:orderSource@t.order_source:int",
                "=:payStatus@t.pay_is:int",
                "=:payWay@t.pay_way:int",
        });

        orderMPJQueryWrapper
                .leftJoin("?_order_goods OG ON t.id=OG.order_id".replace("?_", GlobalConfig.tablePrefix))
                .leftJoin("?_user U ON t.user_id=U.id".replace("?_", GlobalConfig.tablePrefix))
                .eq("t.is_delete", 0)
                .orderByDesc("t.id");

        Map<String, Object> statistics = __statistics(orderMPJQueryWrapper.clone());

        if (StringUtils.isNotNull(orderSearchValidate.getType()) && orderSearchValidate.getType() > 0) {
            orderMPJQueryWrapper.eq("t.order_status", orderSearchValidate.getType());
        }

        orderMPJQueryWrapper
                .select("DISTINCT t.id,t.user_id,t.order_sn,t.pay_is,t.pay_money,t.pay_way,t.order_status,t.express_is,t.cancel_time," +
                        "t.address_contact,t.address_mobile,t.address_content,U.sn as user_sn,U.avatar,U.nickname");

        IPage<OrderInfoListVo> iPage = orderMapper.selectJoinPage(
                new Page<>(pageNo, pageSize),
                OrderInfoListVo.class,
                orderMPJQueryWrapper);

        List<OrderManageListedVo> orderList = new ArrayList<>();
        for (OrderInfoListVo record : iPage.getRecords()) {
            Order orders = orderMapper.selectOne(
                    new QueryWrapper<Order>()
                    .eq("order_sn", record.getOrderSn())
                    .last("limit 1"));
            OrderManageListedVo orderManageListedVo = new OrderManageListedVo();
            BeanUtils.copyProperties(record, orderManageListedVo);
            orderManageListedVo.setPayIsMsg(PaymentEnum.getPayStatusMsg(record.getPayIs()));
            orderManageListedVo.setOrderStatusMsg(OrderEnum.getOrderStatusMsg(record.getOrderStatus()));
            orderManageListedVo.setPayTypeMsg(OrderEnum.getOrderPayWayMsg(record.getPayWay()));
            orderManageListedVo.setPayMoney(record.getPayIs().equals(1) ? record.getPayMoney().toString() : "-");

            orderManageListedVo.setCancelBtn(this.__cancelBtn(record.getOrderStatus()));
            orderManageListedVo.setConfirmBtn(this.__confirmBtn(record.getOrderStatus()));
            orderManageListedVo.setDeleteBtn(this.__deleteBtn(record.getOrderStatus()));
            orderManageListedVo.setDeliverBtn(this.__deliverBtn(record.getOrderStatus()));
            orderManageListedVo.setLogisticsBtn(this.__logisticsBtn(record.getOrderStatus(), record.getExpressIs()));
            orderManageListedVo.setRefundBtn(this.__refundBtn(record.getOrderStatus(), record.getExpressIs(),orders.getConfirmTime() == null ? 0 : orders.getConfirmTime()));
            orderManageListedVo.setAvatar(UrlUtils.toAbsoluteUrl(record.getAvatar()));


            List<OrderGoods> orderLists = orderGoodsMapper.selectList(
                    new QueryWrapper<OrderGoods>()
                        .eq("order_id", record.getId())
                        .select("id,goods_id,goods_name,goods_code,goods_image,goods_sku_id,goods_sku_value,goods_num,goods_price,need_pay_money"));

            List<OrderGoodsListVo> orderGoodsListVos = new ArrayList<>();
            for (OrderGoods list : orderLists) {
                list.setGoodsImage(UrlUtils.toAbsoluteUrl(list.getGoodsImage()));
                OrderGoodsListVo orderGoodsListVo = new OrderGoodsListVo();
                BeanUtils.copyProperties(list,orderGoodsListVo);
                orderGoodsListVos.add(orderGoodsListVo);
            }

            orderManageListedVo.setOrderGoodsList(orderGoodsListVos);
            orderList.add(orderManageListedVo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), orderList, statistics);
    }

    /**
     * 订单详情
     *
     * @author cjh
     * @param id 订单ID
     * @return OrderBcDetailVo
     */
    @Override
    public OrderManageDetailVo detail(Integer id){
        Order order = orderMapper.selectOne(
                new QueryWrapper<Order>()
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(order, "订单不存在!");

        // 订单用户
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("id", order.getUserId())
                .last("limit 1"));

        // 订单商品
        List<OrderGoods> orderGoodsListVos = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", order.getId()));
        List<OrderGoodsListVo> orderGoodsListVoList = new ArrayList<>();
        for (OrderGoods orderGoodsList : orderGoodsListVos) {
            OrderGoodsListVo orderGoodsListVo = new OrderGoodsListVo();
            BeanUtils.copyProperties(orderGoodsList,orderGoodsListVo);
            orderGoodsListVo.setAfterMsg(OrderAfterEnum.afterSaleMsg(orderGoodsList.getAfterSale()));
            orderGoodsListVo.setGoodsImage(UrlUtils.toAbsoluteUrl(orderGoodsList.getGoodsImage()));
            orderGoodsListVoList.add(orderGoodsListVo);
        }

        // 订单详情
        OrderManageDetailVo orderManageDetailVo = new OrderManageDetailVo();
        BeanUtils.copyProperties(order, orderManageDetailVo);
        orderManageDetailVo.setNickname(user.getNickname());
        orderManageDetailVo.setOrderGoodsList(orderGoodsListVoList);
        orderManageDetailVo.setOrderSourceMsg(ClientEnum.getMsgByCode(order.getOrderSource()));
        orderManageDetailVo.setPayWayMsg(PaymentEnum.getPayWayMsg(order.getPayWay()));
        orderManageDetailVo.setExpressIsMsg(DeliverEnum.getDeliverIsMsg(order.getExpressIs()));
        orderManageDetailVo.setDeliveryTypeMsg(DeliverEnum.getDeliverTypeMsg(order.getDeliveryType()));
        orderManageDetailVo.setOrderStatusMsg(OrderEnum.getOrderStatusMsg(order.getOrderStatus()));
        orderManageDetailVo.setPayIsMsg(PaymentEnum.getPayStatusMsg(order.getPayIs()));
        orderManageDetailVo.setPayTime(order.getPayTime() > 0 ? TimeUtils.timestampToDate(order.getPayTime()) : "-");
        orderManageDetailVo.setCancelTime(order.getCancelTime() > 0 ? TimeUtils.timestampToDate(order.getCancelTime()) : "-");
        orderManageDetailVo.setConfirmTime(order.getConfirmTime() > 0 ? TimeUtils.timestampToDate(order.getConfirmTime()) : "-");
        orderManageDetailVo.setExpressTime(order.getExpressTime() > 0 ? TimeUtils.timestampToDate(order.getExpressTime()) : "-");
        orderManageDetailVo.setCreateTime(TimeUtils.timestampToDate(order.getCreateTime()));

        orderManageDetailVo.setDeleteBtn(this.__deleteBtn(order.getOrderStatus()));
        orderManageDetailVo.setDeliverBtn(this.__deliverBtn(order.getOrderStatus()));
        orderManageDetailVo.setLogisticsBtn(this.__logisticsBtn(order.getOrderStatus(), order.getExpressIs()));
        orderManageDetailVo.setRefundBtn(this.__refundBtn(order.getOrderStatus(), order.getExpressIs(),order.getConfirmTime() == null ? 0 : order.getConfirmTime()));
        orderManageDetailVo.setCancelBtn(this.__cancelBtn(order.getOrderStatus()));
        orderManageDetailVo.setConfirmBtn(this.__confirmBtn(order.getOrderStatus()));

        if(order.getExpressId() > 0){
            ExpressCompany expressCompany = expressCompanyMapper.selectOne(new QueryWrapper<ExpressCompany>()
                    .eq("id", order.getExpressId())
                    .eq("is_delete", 0)
                    .last("limit 1"));
            orderManageDetailVo.setExpressCompanyName(expressCompany.getName());
            orderManageDetailVo.setExpressConfirmTime(order.getConfirmTime() <= 0 ? "-" : TimeUtils.timestampToDate(order.getConfirmTime()));
        }

        List<LogOrder> orderLogList  = logOrderMapper.selectList(new QueryWrapper<LogOrder>().eq("order_id", order.getId()));
        List<OrderLogListVo> orderLogListVoList = new ArrayList<>();
        for (LogOrder orderLog : orderLogList) {
            OrderLogListVo orderLogListVo = new OrderLogListVo();
            BeanUtils.copyProperties(orderLog,orderLogListVo);
            switch (orderLog.getType()){
                case 1:
                    orderLogListVo.setOperatorName("系统");
                    break;
                case 2:
                    SystemAuthAdmin systemAuthAdmin = systemAuthAdminMapper.selectOne(new QueryWrapper<SystemAuthAdmin>()
                            .eq("id", orderLog.getOperatorId()).last("limit 1"));
                    orderLogListVo.setOperatorName(systemAuthAdmin.getNickname());
                    break;
                case 3:
                    User operatorUser = userMapper.selectOne(new QueryWrapper<User>()
                            .eq("id", orderLog.getOperatorId()).last("limit 1"));
                    if(null != operatorUser && StringUtils.isNotEmpty(operatorUser.getNickname())) {
                    	orderLogListVo.setOperatorName(operatorUser.getNickname());
                    }
                    break;
            }
            orderLogListVo.setCreateTime(TimeUtils.timestampToDate(orderLog.getCreateTime()));
            orderLogListVoList.add(orderLogListVo);
        }

        orderManageDetailVo.setOrderLogList(orderLogListVoList);
        return orderManageDetailVo;
    }

    /**
     * 订单取消
     *
     * @author fzr
     * @param id 订单ID
     * @param adminId 管理员ID
     */
    @Override
    public void cancel(Integer id, Integer adminId) {
        Order order = orderMapper.selectOne(
                new QueryWrapper<Order>()
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(order, "订单不存在!");

        if (!order.getOrderStatus().equals(OrderEnum.ORDER_STATUS_WAIT_PAY.getCode()) &&
            !order.getOrderStatus().equals(OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) &&
            !order.getOrderStatus().equals(OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode())) {
            throw new OperateException("订单不允许取消");
        }

        OrderAfter orderAfterM = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
                .eq("order_id", id)
                .in("after_status", Arrays.asList(1, 2))
                .eq("is_delete", 0)
                .last("limit 1"));

        if (StringUtils.isNotNull(orderAfterM)) {
            throw new OperateException("正在售后的订单不能取消");
        }

        if (order.getOrderStatus().equals(OrderEnum.ORDER_STATUS_WAIT_PAY.getCode())) {
            // 未支付取消
            order.setOrderStatus(OrderEnum.ORDER_STATUS_CANCEL.getCode());
            order.setCancelTime(System.currentTimeMillis() / 1000);
            orderMapper.updateById(order);
        } else {
            // 已支付取消
            TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
            try {
                // 退款金额 (已发货不退运费)
                BigDecimal refundMoney = order.getNeedPayMoney();
                if (order.getExpressIs().equals(1)) {
                    refundMoney = order.getNeedPayMoney().subtract(order.getExpressMoney());
                }

                // 整单售后
                if (order.getPayIs().equals(PaymentEnum.OK_PAID.getCode())) {
                    OrderAfter orderAfter = null;
                    RefundRecord refundRecord = null;
                    RefundLog refundLog = null;
                    try {
                        // 写入售后订单
                        String afterSn = orderAfterMapper.randMakeOrderSn("after_sn");
                        orderAfter = new OrderAfter();
                        orderAfter.setAfterSn(afterSn);
                        orderAfter.setUserId(order.getUserId());
                        orderAfter.setOrderId(order.getId());
                        orderAfter.setRefundWay(1);
                        orderAfter.setAfterType(OrderAfterEnum.AFTER_TYPE_ORDER.getCode());
                        orderAfter.setRefundType(OrderAfterEnum.METHOD_ONLY_REFUND.getCode());
                        orderAfter.setRefundReason(LogOrderAfterEnum.BUYER_CANCEL_ORDER.getMsg());
                        orderAfter.setRefundMoney(refundMoney);
                        orderAfter.setRefundRemark("系统发起整单退款");
                        orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_ING.getCode());
                        orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_ING_SELLER_REFUND_ING.getCode());
                        orderAfter.setCreateTime(System.currentTimeMillis() / 1000);
                        orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
                        orderAfterMapper.insert(orderAfter);

                        // 写入售后商品
                        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", id));
                        for (OrderGoods item : orderGoodsList) {
                            // 退款金额 (已发货不退运费)
                            BigDecimal goodsRefundMoney = item.getNeedPayMoney();
                            if (order.getExpressIs().equals(1)) {
                                goodsRefundMoney = item.getNeedPayMoney().subtract(item.getExpressMoney());
                            }

                            OrderAfterGoods afterGoods = new OrderAfterGoods();
                            afterGoods.setOrderId(item.getOrderId());
                            afterGoods.setOrderAfterId(orderAfter.getId());
                            afterGoods.setOrderGoodsId(item.getId());
                            afterGoods.setGoodsId(item.getGoodsId());
                            afterGoods.setGoodsSkuId(item.getGoodsSkuId());
                            afterGoods.setGoodsNum(item.getGoodsNum());
                            afterGoods.setGoodsPrice(item.getGoodsPrice());
                            afterGoods.setRefundMoney(goodsRefundMoney);
                            afterGoods.setCreateTime(System.currentTimeMillis() / 1000);
                            afterGoods.setUpdateTime(System.currentTimeMillis() / 1000);
                            orderAfterGoodsMapper.insert(afterGoods);
                        }

                        // 生成售后日志
                        Integer roleSeller = LogOrderAfterEnum.TYPE_ADMIN.getCode();
                        logOrderAfterMapper.add(roleSeller, adminId, id, LogOrderAfterEnum.SELLER_CANCEL_ORDER.getMsg());

                        // 生成退款记录
                        String refundSn = refundRecordMapper.randMakeOrderSn("sn");
                        refundRecord = new RefundRecord();
                        refundRecord.setSn(refundSn);
                        refundRecord.setOrderSn(order.getOrderSn());
                        refundRecord.setOrderId(order.getId());
                        refundRecord.setUserId(order.getUserId());
                        refundRecord.setRefundType(RefundEnum.TYPE_ADMIN.getCode());
                        refundRecord.setOrderType(RefundEnum.getOrderType(RefundEnum.ORDER_TYPE_ORDER.getCode()));
                        refundRecord.setOrderAmount(order.getPayMoney());
                        refundRecord.setRefundAmount(orderAfter.getRefundMoney());
                        refundRecord.setTransactionId(order.getTransactionId());
                        refundRecord.setRefundWay(order.getPayWay());
                        refundRecord.setCreateTime(System.currentTimeMillis() / 1000);
                        refundRecord.setUpdateTime(System.currentTimeMillis() / 1000);
                        refundRecordMapper.insert(refundRecord);

                        // 生成退款日志
                        refundLog = new RefundLog();
                        refundLog.setSn(refundLogMapper.randMakeOrderSn("sn"));
                        refundLog.setRecordId(refundRecord.getId());
                        refundLog.setUserId(order.getUserId());
                        refundLog.setHandleId(adminId);
                        refundLog.setOrderAmount(order.getPayMoney());
                        refundLog.setRefundAmount(orderAfter.getRefundMoney());
                        refundLog.setRefundStatus(RefundEnum.REFUND_ING.getCode());
                        refundLog.setCreateTime(System.currentTimeMillis() / 1000);
                        refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
                        refundLogMapper.insert(refundLog);

                        // 发起退款请求
                        switch (order.getPayWay()) {
                            case 1: // 余额
                                User user = userMapper.selectById(order.getUserId());
                                BigDecimal earnings = BigDecimal.ZERO;
                                if(user.getEarnings() == null){
                                    earnings = earnings.add(orderAfter.getRefundMoney());
                                }else{
                                    earnings = user.getEarnings().add(orderAfter.getRefundMoney());
                                }
                                user.setEarnings(earnings);
                                user.setUpdateTime(System.currentTimeMillis() / 1000);
                                /*user.setMoney(user.getMoney().add(orderAfter.getRefundMoney()));
                                user.setUpdateTime(System.currentTimeMillis() / 1000);*/
                                userMapper.updateById(user);

                                Integer logMoneyType = LogMoneyEnum.BNW_INC_AFTER_SALE.getCode();
                                String logMoneyRemark = "售后退还余额";
                                logMoneyMapper.add(
                                        user.getId(),
                                        logMoneyType,
                                        orderAfter.getRefundMoney(),
                                        order.getId(),
                                        order.getOrderSn(),
                                        logMoneyRemark,
                                        null);

                                break;
                            case 2: // 微信
                                RefundRequestV3 requestV3 = new RefundRequestV3();
                                requestV3.setTransactionId(order.getTransactionId());
                                requestV3.setOutTradeNo(order.getOrderSn());
                                requestV3.setOutRefundNo(refundSn);
                                requestV3.setTotalAmount(AmountUtil.yuan2Fen(order.getPayMoney().toString()));
                                requestV3.setRefundAmount(AmountUtil.yuan2Fen(orderAfter.getRefundMoney().toString()));
                                WxPayDriver.refund(requestV3);
                                break;
                            case 3:
                                AliPayRefundRequest request = new AliPayRefundRequest();
                                request.setTransactionId(order.getTransactionId());
                                request.setOutTradeNo(order.getOrderSn());
                                request.setOutRefundNo(refundSn);
                                request.setTotalAmount(order.getPayMoney());
                                request.setRefundAmount(orderAfter.getRefundMoney());
                                AliPayDriver.refund(request);
                                break;
                        }

                        // 退款记录更新
                        refundRecord.setRefundStatus(RefundEnum.REFUND_SUCCESS.getCode());
                        refundRecord.setUpdateTime(System.currentTimeMillis() / 1000);
                        refundRecordMapper.updateById(refundRecord);

                        // 退款日志更新
                        refundLog.setRefundStatus(RefundEnum.REFUND_SUCCESS.getCode());
                        refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
                        refundLogMapper.updateById(refundLog);

                        // 更新售后状态
                        List<OrderAfterGoods> orderAfterGoods = orderAfterGoodsMapper.selectList(new QueryWrapper<OrderAfterGoods>().eq("order_after_id", orderAfter.getId()));
                        for (OrderAfterGoods oag : orderAfterGoods) {
                            OrderGoods orderGoods = new OrderGoods();
                            orderGoods.setAfterSale(3);
                            orderGoods.setUpdateTime(System.currentTimeMillis() / 1000);
                            orderGoodsMapper.update(orderGoods, new QueryWrapper<OrderGoods>().eq("id", oag.getOrderGoodsId()));
                        }

                        // 变更成功状态
                        orderAfter.setRefundSn(refundSn);
                        orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_SUCCESS.getCode());
                        orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_SUCCESS.getCode());
                        orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
                        orderAfterMapper.updateById(orderAfter);
                    } catch (Exception e) {
                        if (StringUtils.isNotNull(orderAfter)) {
                            orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_ING_SELLER_REFUND_ING.getCode());
                            orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
                            orderAfterMapper.updateById(orderAfter);
                        }

                        if (StringUtils.isNotNull(refundRecord)) {
                            refundRecord.setRefundStatus(RefundEnum.REFUND_ERROR.getCode());
                            refundRecord.setUpdateTime(System.currentTimeMillis() / (1000));
                            refundRecordMapper.updateById(refundRecord);
                        }

                        if (StringUtils.isNotNull(refundLog)) {
                            refundLog.setRefundMsg(e.getMessage());
                            refundLog.setRefundStatus(RefundEnum.REFUND_ERROR.getCode());
                            refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
                            refundLogMapper.updateById(refundLog);
                        }

                        throw new Exception(e.getMessage());
                    }
                }

                // 订单状态
                order.setOrderStatus(OrderEnum.ORDER_STATUS_CANCEL.getCode());
                order.setCancelTime(System.currentTimeMillis() / 1000);
                orderMapper.updateById(order);

                // 订单日志
                Integer channel = OrderLogEnum.CHANNEL_ADMIN_CANCEL_ORDER.getCode();
                logOrderMapper.add(
                        order.getId(),
                        OrderLogEnum.TYPE_SYSTEM.getCode(),
                        channel,
                        adminId,
                        OrderLogEnum.getValue(channel));

                // 相关分销订单更新为失效
                DistributionOrder distributionOrder = new DistributionOrder();
                distributionOrder.setStatus(DistributionEnum.ORDER_EXPIRED.getCode());
                distributionOrder.setUpdateTime(System.currentTimeMillis() / 1000);
                distributionOrderMapper.update(distributionOrder, new QueryWrapper<DistributionOrder>()
                        .eq("order_id", order.getId()));

                transactionManager.commit(transactionStatus);
            } catch (Exception e) {
                assert transactionManager != null;
                transactionManager.rollback(transactionStatus);
                throw new OperateException(e.getMessage());
            }
        }
    }

    /**
     * 订单备注
     *
     * @author fzr
     * @param orderId 订单ID
     * @param remarks 备注信息
     */
    @Override
    public void remarks(Integer orderId, String remarks) {
        Order order = orderMapper.selectOne(
                new QueryWrapper<Order>()
                        .eq("id", orderId)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(order, "订单不存在!");


        order.setShopRemark(remarks);
        order.setUpdateTime(System.currentTimeMillis() / 1000);
        orderMapper.updateById(order);
    }

    /**
     * 订单发货
     *
     * @author fzr
     * @param adminId 管理员ID
     * @param sendDeliveryValidate 发货参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendDelivery(Integer adminId, OrderSendDeliveryValidate sendDeliveryValidate) {
        Order order = orderMapper.selectById(sendDeliveryValidate.getOrderId());
        Assert.notNull(order, "订单不存在了!");

        Integer expressId = 0;
        String expressName = "";
        String invoiceNo = "";
        String codeWx = "";
        if (sendDeliveryValidate.getSendType().equals(1)) {
            ExpressCompany expressCompany = expressCompanyMapper.selectOne(
                    new QueryWrapper<ExpressCompany>()
                            .eq("id", sendDeliveryValidate.getExpressId())
                            .eq("is_delete", 0)
                            .last("limit 1"));

            Assert.notNull(expressCompany, "快递公司不存在!");
            expressId = expressCompany.getId();
            expressName = expressCompany.getName();
            invoiceNo = sendDeliveryValidate.getInvoiceNo();
            codeWx = expressCompany.getCodeWx();
        }

        OrderDelivery orderDelivery = new OrderDelivery();
        orderDelivery.setOrderId(order.getId());
        orderDelivery.setUserId(order.getUserId());
        orderDelivery.setAdminId(adminId);
        orderDelivery.setOrderSn(order.getOrderSn());
        orderDelivery.setContact(order.getAddressContact());
        orderDelivery.setMobile(order.getAddressMobile());
        orderDelivery.setProvince(0);
        orderDelivery.setCity(0);
        orderDelivery.setDistrict(0);
        orderDelivery.setInvoiceNo(invoiceNo);
        orderDelivery.setExpressId(expressId);
        orderDelivery.setExpressName(expressName);

        orderDelivery.setExpressStatus(DeliverEnum.SHIPPED.getCode());
        orderDelivery.setSendType(sendDeliveryValidate.getSendType());
        orderDelivery.setRemark(sendDeliveryValidate.getRemark());
        orderDelivery.setCreateTime(System.currentTimeMillis() / 1000);
        orderDelivery.setUpdateTime(System.currentTimeMillis() / 1000);
        orderDeliveryMapper.insert(orderDelivery);

        order.setOrderStatus(OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode());
        order.setExpressIs(DeliverEnum.SHIPPED.getCode());
        order.setExpressNo(sendDeliveryValidate.getInvoiceNo());
        order.setExpressId(sendDeliveryValidate.getExpressId());
        order.setExpressTime(System.currentTimeMillis() / 1000);
        order.setUpdateTime(System.currentTimeMillis() / 1000);
        orderMapper.updateById(order);

        // 修改发货通知状态
        LambdaUpdateWrapper<OrderUrgeMsg> updateWrapper = new LambdaUpdateWrapper<OrderUrgeMsg>();
        updateWrapper.eq(OrderUrgeMsg::getOrderId, sendDeliveryValidate.getOrderId());
        OrderUrgeMsg urge = new OrderUrgeMsg();
        urge.setOrderStatus(1);
        urge.setUpdateTime(TimeUtils.timestamp());
        orderUrgeMsgMapper.update(urge, updateWrapper);
        
        // 订单日志
        Integer channel = OrderLogEnum.CHANNEL_SHOP_DELIVERY_ORDER.getCode();
        logOrderMapper.add(
                order.getId(),
                OrderLogEnum.TYPE_SYSTEM.getCode(),
                channel,
                adminId,
                OrderLogEnum.getValue(channel));

        // 发货通知
        try {
//            NoticeSmsVo UserParams = new NoticeSmsVo()
//                    .setScene(NoticeEnum.ORDER_SHIP_NOTICE.getCode())
//                    .setMobile(order.getAddressMobile())
//                    .setExpire(900)
//                    .setParams(new String[]{
//                            "nickname:" + order.getAddressContact(),
//                            "order_sn:" + order.getOrderSn()
//                    });
//            NoticeDriver.handle(UserParams);
        	// 微信通知发货
        	if(1 == order.getOrderSource() && 2 == order.getPayWay()) {
        		Integer logisticsType = 1;
        		if(sendDeliveryValidate.getSendType() == 2) {
        			logisticsType = 3;
        		}
        		String itemDesc = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoods>()
        				.eq(OrderGoods::getOrderId, order.getId()).select(OrderGoods::getGoodsName)).getGoodsName();
        		String openid = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>()
        				.eq(UserAuth::getUserId, order.getUserId()).select(UserAuth::getMnpOpenid)).getMnpOpenid();
        		WeiXinApplication.getWxDeliverGoodsVo(order.getTransactionId(), logisticsType, itemDesc, invoiceNo, codeWx, openid, order.getAddressMobile());
        	}
        } catch (Exception ignored) {}
        //如果是无物流配送 就直接确认收货
        if(sendDeliveryValidate.getSendType() == 2){
            confirm(order.getId());
        }
    }



    /**
     * 确认收货
     *
     * @author fzr
     * @param orderId 订单ID
     * @param adminId 管理员ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void takeDelivery(Integer orderId, Integer adminId) {
        Order order = orderMapper.selectById(orderId);
        Assert.notNull(order, "订单不存在了!");

        // 订单更新
        order.setOrderStatus(OrderEnum.ORDER_STATUS_COMPLETED.getCode());
        order.setAfterDeadline(getAfterSaleDeadline());
        order.setConfirmTime(System.currentTimeMillis() / 1000);
        order.setUpdateTime(System.currentTimeMillis() / 1000);
        orderMapper.updateById(order);

        // 订单日志
        Integer channel = OrderLogEnum.CHANNEL_SHOP_CONFIRM_ORDER.getCode();
        logOrderMapper.add(
                order.getId(),
                OrderLogEnum.TYPE_SYSTEM.getCode(),
                channel,
                adminId,
                OrderLogEnum.getValue(channel));
    }

    /**
     * 查看物流
     *
     * @author fzr
     * @param orderId 订单ID
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> logistics(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        Assert.notNull(order, "订单不存在!");

        ExpressCompany expressCompany = expressCompanyMapper.selectById(order.getExpressId());
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));

        List<Map<String, Object>> goods = new LinkedList<>();
        for (OrderGoods orderGoods : orderGoodsList) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("goodsCode", orderGoods.getGoodsCode());
            map.put("goodsImage", UrlUtils.toAbsoluteUrl(orderGoods.getGoodsImage()));
            map.put("goodsName", orderGoods.getGoodsName());
            map.put("goodsSkuValue", orderGoods.getGoodsSkuValue());
            map.put("goodsNum", orderGoods.getGoodsNum());
            map.put("goodsPrice", orderGoods.getGoodsPrice());
            map.put("goodsMoney", orderGoods.getMoney());
            map.put("afterSale", orderGoods.getAfterSale());
            map.put("afterSaleMsg", OrderAfterEnum.afterSaleMsg(orderGoods.getAfterSale()));
            goods.add(map);
        }

        Map<String, Object> express = new LinkedHashMap<>();
        express.put("expressName", StringUtils.isNotNull(expressCompany) ? expressCompany.getName() : "-");
        express.put("expressNo", order.getExpressNo());
        express.put("expressTime", TimeUtils.timestampToDate(order.getExpressTime()));

        Map<String, Object> response = new LinkedHashMap<>();
        response.put("goods", goods);
        response.put("express", express);

        // 查询物流
        List<KdTrackResultVo> track = new LinkedList<>();
        String trackError = null;

        if (StringUtils.isNotNull(expressCompany)) {
            try {
                String expressEngine = ConfigUtils.get("logistics", "engine", "");
                if (StringUtils.isEmpty(expressEngine)) {
                    throw new OperateException("请联系管理员配置物流设置");
                }
                // 快递查询参数
                KdQueryTrackParam kdQueryTrackParam = new KdQueryTrackParam();
                // 物流公司编码
                String expressCode = expressCompany.getCodeKdniao();
                if (expressEngine.equals("kd100")) {
                    expressCode = expressCompany.getCodeKd100();
                    if (expressCode.equals("SF") || expressCode.equals("sf") || expressCode.equals("shunfeng")) {
                        kdQueryTrackParam.setPhone(order.getAddressMobile());
                    }
                } else {
                    if (expressCode.equals("SF")) {
                        kdQueryTrackParam.setPhone(order.getAddressMobile().substring(order.getAddressMobile().length() - 4));
                    }
                }
                kdQueryTrackParam.setCom(expressCode);
                kdQueryTrackParam.setNum(order.getExpressNo());
                track = (new DeliveryDriver()).queryTrack(kdQueryTrackParam);
            } catch (OperateException e) {
                trackError = e.getMsg();
            }
        }

        Map<String, Object> trajectory = new LinkedHashMap<>();
        trajectory.put("track", track);
        trajectory.put("trackError", trackError);
        response.put("trajectory", trajectory);

        return response;
    }

    /**
     * 当前售后时间
     *
     * @author mjf
     * @return Long
     */
    @Override
    public Long getAfterSaleDeadline() {
        float afterSalesDay = Float.parseFloat(ConfigUtils.get("trade", "afterSalesDay", "-1"));
        long afterSaleDeadline = TimeUtils.timestamp();
        if (afterSalesDay != -1) {
            afterSaleDeadline = (long)(afterSalesDay *24 * 60 * 60) + TimeUtils.timestamp();
        }
        return afterSaleDeadline;
    }

    /**
     * 订单统计
     *
     * @author cjh
     * @param mpjQueryWrapper 搜索器
     * @return Map<Object>
     */
    private Map<String, Object> __statistics(MPJQueryWrapper<Order> mpjQueryWrapper) {
        Integer waitPay     = OrderEnum.ORDER_STATUS_WAIT_PAY.getCode();
        Integer waitDeliver = OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode();
        Integer takeDeliver = OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode();
        Integer completed   = OrderEnum.ORDER_STATUS_COMPLETED.getCode();
        Integer cancel      = OrderEnum.ORDER_STATUS_CANCEL.getCode();

        Map<String, Object> statistics = new LinkedHashMap<>();
        mpjQueryWrapper.select("DISTINCT t.id");

        // 全部
        MPJQueryWrapper<Order> allNumQuery = mpjQueryWrapper.clone();
        statistics.put("allNum", orderMapper.selectCount(allNumQuery.eq("t.is_delete", 0)));
        // 待付款
        MPJQueryWrapper<Order> waitPayNumQuery = mpjQueryWrapper.clone();
        statistics.put("waitPayNum", orderMapper.selectCount(waitPayNumQuery.eq("t.order_status", waitPay)));
        // 待发货
        MPJQueryWrapper<Order> waitDeliverNumQuery = mpjQueryWrapper.clone();
        statistics.put("waitDeliverNum", orderMapper.selectCount(waitDeliverNumQuery.eq("t.order_status", waitDeliver)));
        // 待收货
        MPJQueryWrapper<Order> takeDeliverNumQuery = mpjQueryWrapper.clone();
        statistics.put("takeDeliverNum", orderMapper.selectCount(takeDeliverNumQuery.eq("t.order_status", takeDeliver)));
        // 已完成
        MPJQueryWrapper<Order> completedNumQuery = mpjQueryWrapper.clone();
        statistics.put("completedNum", orderMapper.selectCount(completedNumQuery.eq("t.order_status", completed)));
        // 已取消
        MPJQueryWrapper<Order> cancelNumQuery = mpjQueryWrapper.clone();
        statistics.put("cancelNum", orderMapper.selectCount(cancelNumQuery.eq("t.order_status", cancel)));

        return statistics;
    }

    /**
     * 获取取消按钮
     *
     * @author cjhao
     * @return Integer
     */
    private Integer __cancelBtn(Integer orderStatus) {
        int btn = 0;
        if(!orderStatus.equals(OrderEnum.ORDER_STATUS_CANCEL.getCode()) &&
           !orderStatus.equals(OrderEnum.ORDER_STATUS_COMPLETED.getCode())){
            btn = 1;
        }
        return btn;
    }

    /**
     * 确定按钮
     *
     * @author cjh
     * @param orderStatus 订单状态
     * @return Integer
     */
    private Integer __confirmBtn(Integer orderStatus) {
        int btn = 0;
        if(OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == orderStatus){
            btn = 1;
        }
        return btn;
    }

    /**
     * 删除按钮
     *
     * @author cjh
     * @param orderStatus 订单状态
     * @return Integer
     */
    private Integer __deleteBtn(Integer orderStatus) {
        int btn = 0;
        if(OrderEnum.ORDER_STATUS_COMPLETED.getCode() == orderStatus ||
           OrderEnum.ORDER_STATUS_CANCEL.getCode() == orderStatus) {
            btn = 1;
        }
        return btn;
    }

    /**
     * 发货按钮
     *
     * @author cjh
     * @param orderStatus 数据
     * @return Integer
     */
    private Integer __deliverBtn(Integer orderStatus) {
        int btn = 0;
        if(OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode() == orderStatus) {
            btn = 1;
        }
        return btn;
    }

    /**
     * 查看物流按钮
     *
     * @author cjhao
     * @param orderStatus 订单状态
     * @param expressIs 发货状态
     * @return Integer
     */
    private Integer __logisticsBtn(Integer orderStatus, Integer expressIs) {
        int btn = 0;
        if(OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == orderStatus &&
           1 == expressIs) {
            btn = 1;
        }
        return btn;
    }

    /**
     * 获取退款按钮
     *
     * @author cjh
     * @param orderStatus 订单状态
     * @param expressIs 发货状态
     * @param confirm_time 收货时间
     * @return Integer
     */
    private Integer __refundBtn(Integer orderStatus, Integer expressIs,Long confirm_time) {
        int btn = 0;
        if(OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == orderStatus &&
                1 == expressIs) {
            btn = 1;
        }
        return btn;

    }
    private BigDecimal hundred = new BigDecimal("100");

    public void confirm(Integer id){
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");
		if (order.getOrderStatus() <= OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			throw new OperateException("订单未发货");
		}
		if (order.getOrderStatus() >= OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			throw new OperateException("订单已完成");
		}
		Integer userId = order.getUserId();
		// 更新信息
		order.setOrderStatus(OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		order.setConfirmTime(System.currentTimeMillis() / 1000);
		// 售后截止时间
		order.setAfterDeadline(__getAfterSaleDeadline());
		orderMapper.updateById(order);
		// 订单日志
		logOrderMapper.add(order.getId(),
				OrderLogEnum.TYPE_USER.getCode(),
				OrderLogEnum.CHANNEL_USER_CONFIRM_ORDER.getCode(),
				userId,OrderLogEnum.CHANNEL_USER_CONFIRM_ORDER.getMsg());

		BigDecimal marketPrice = BigDecimal.ZERO;
		// 确认收货检验是否有分享者
		List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, id));
		if(order.getPayWay() != 4) {
			User user = userMapper.selectById(order.getUserId());
			Integer userLevelCurr = 1;
			// 查询用户VIP等级
			Distribution distributionCurr = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
			if(null != distributionCurr && null != distributionCurr.getExpireTime() && distributionCurr.getExpireTime() > TimeUtils.timestamp()) {
				userLevelCurr = distributionCurr.getLevelId();
			}
			for (OrderGoods orderGoods : orderGoodsList) {
				// 查询产品分佣类型
				Goods goods = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoods.getGoodsId()).ne(Goods::getCommissionType, 3));
				if(null == goods) {
					continue;
				}
				// 获取购买的规格
				GoodsSku goodsSku = goodsSkuMapper.selectById(orderGoods.getGoodsSkuId());
				if(null == goodsSku) {
					continue;
				}
				BigDecimal couponAmount = BigDecimal.ZERO;
				// 领券优惠金额
				if(StringUtils.isNotEmpty(order.getCouponListId())) {
					if(!"0".equals(order.getCouponListId())){
						BigDecimal _m1 = order.getNeedPayMoney().subtract(order.getExpressMoney());
						BigDecimal _m2 = _m1.divide(order.getGoodsMoney(),2, RoundingMode.HALF_UP);
						BigDecimal _m3 = _m2.multiply(orderGoods.getMoney());
						couponAmount = orderGoods.getMoney().subtract(_m3);
					}
				}
				BigDecimal price = BigDecimal.ZERO;
				// 计算产品类型且分佣金额
				if(null != goods.getCashbackRatio() && goods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
					if(goods.getCommissionType() == 1) {	// 利润 【产品售价-产品供货价-领券优惠金额】
						price = goodsSku.getPrice().subtract(goodsSku.getMarketPrice()).subtract(couponAmount);

					}else {	// 差价 【产品售价*百分比（如5%）-领券优惠金额】
						BigDecimal divide = goods.getCommissionRatio().divide(hundred,2, RoundingMode.HALF_UP);
						BigDecimal multiply = goodsSku.getPrice().multiply(divide);
						price = multiply.subtract(couponAmount);
					}
				}
				price = price.multiply(new BigDecimal(orderGoods.getGoodsNum()));
				// 下单再返
				cashback(goods, orderGoods.getUserId(), order,price);
				// 分享分佣
				if(price.compareTo(BigDecimal.ZERO) > 0 && orderGoods.getShareUserId() > 0) {
					Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, orderGoods.getShareUserId()));
					if(null != distribution) {
						Integer userLevel = distribution.getLevelId();
						if(distribution.getExpireTime() < TimeUtils.timestamp()) {
							userLevel = 1;
						}
						BigDecimal cashbackAmount = BigDecimal.ZERO;
						// 计算等级分佣
						if(2 == userLevel) {
							BigDecimal divide = goods.getLevel1Silver().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}else if(3 == userLevel) {
							BigDecimal divide = goods.getLevel1Gold().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}else if(4 == userLevel) {
							BigDecimal divide = goods.getLevel1Diamond().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}
						if(cashbackAmount.compareTo(BigDecimal.ZERO) > 0) {
							if(userLevel >= 4) {
								userMapper.update(null, new UpdateWrapper<User>()
										.eq("id", orderGoods.getShareUserId())
										.setSql("earnings = earnings+"+ cashbackAmount));
								logEarningsMapper.add(
										orderGoods.getShareUserId(), LogMoneyEnum.UE_INC_GOODS.getCode(), cashbackAmount, goods.getId(), order.getOrderSn(), "分享产品增加余额", "");
								eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(orderGoods.getShareUserId()), "本次获得余额"+cashbackAmount);

							}else {
								userMapper.update(null, new UpdateWrapper<User>()
										.eq("id", orderGoods.getShareUserId())
										.setSql("integral = integral+"+(cashbackAmount.multiply(hundred))));
								logIntegralMapper.add(
										orderGoods.getShareUserId(), LogMoneyEnum.UI_INC_SHARE.getCode(), cashbackAmount.multiply(hundred), goods.getId(), order.getOrderSn(), "分享产品增加金币", "");

								eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(orderGoods.getShareUserId()), "本次获得金币"+cashbackAmount.multiply(hundred));
							}
						}
					}
				}
				// 是否是分佣产品
				__handleCommission(goods, orderGoods.getUserId(), order,price,userLevelCurr,user);
			}
			//下单判断是否需要升级vip
			this.receiveVip(userId,order,orderGoodsList);
		}
		
		for (OrderGoods orderGoods : orderGoodsList) {
			// 获取购买的规格
			GoodsSku goodsSku = goodsSkuMapper.selectById(orderGoods.getGoodsSkuId());
			if(null == goodsSku) {
				continue;
			}
			BigDecimal multiply = goodsSku.getMarketPrice().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
			marketPrice = marketPrice.add(multiply);
		}
		// 增加商户余额
		Shop shop = shopMapper.selectById(order.getShopId());
		System.out.println("商户是否存在："+shop==null);
		System.out.println("商品供货价："+marketPrice);
		if(null != shop && marketPrice.compareTo(BigDecimal.ZERO) > 0) {
			System.out.println("进来这里");
			shop.setTotalAmount(shop.getTotalAmount().add(marketPrice));
			shopMapper.updateById(shop);
		}
    }
    /**
	 * 	计算产品分佣 2024-11-27
	 */

	public void __handleCommission(Goods goods,Integer userId,Order order,BigDecimal price,Integer userLevel,User user) {
		if(price.compareTo(BigDecimal.ZERO) > 0) {
			if(user.getFirstLeader() <= 0) {
				return;
			}
			Distribution distributionFirst = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getFirstLeader()));
			if(distributionFirst == null) {
				return;
			}else if(distributionFirst.getLevelId() <= 1 || distributionFirst.getExpireTime() < TimeUtils.timestamp()){
				return;
			}
			DistributionLevel distributionLevelFirst = distributionLevelMapper.selectById(distributionFirst.getLevelId());

			DistributionLevel distributionLevelSecond = null;
			Distribution distributionSecond = null;
			if(user.getSecondLeader() > 0) {
				distributionSecond = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getSecondLeader()));
				if(null != distributionSecond && distributionSecond.getLevelId() > 1 && distributionSecond.getExpireTime() > TimeUtils.timestamp()) {
					distributionLevelSecond = distributionLevelMapper.selectById(distributionSecond.getLevelId());
				}
			}
			//  所有用户利润1%现金 / 2%
			if(null != distributionLevelFirst.getFirstRatio() && BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).divide(hundred);
				if(distributionFirst.getLevelId() == 6 || distributionFirst.getLevelId() == 7) {
					BigDecimal _earnings = price.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上上级团队利润
			if(null!= distributionLevelSecond && null != distributionLevelSecond.getFirstRatio() && BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionSecond.getLevelId() == 6 || distributionSecond.getLevelId() == 7) {
					BigDecimal _earnings = price.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上级
			if(distributionFirst.getLevelId() >= 4) { // 钻石以上是余额
				BigDecimal ratio = goods.getLevel1Diamond().divide(hundred,2, RoundingMode.HALF_UP);
				BigDecimal _earnings = price.multiply(ratio);
				userMapper.update(null, new UpdateWrapper<User>()
						.eq("id", user.getFirstLeader())
						.setSql("earnings = earnings+"+_earnings));
				logEarningsMapper.add(
						user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上级代理余额", "");
				eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
			}else {	// 钻石以下是金币
				BigDecimal _earnings = BigDecimal.ZERO;
				if(distributionFirst.getLevelId() == 2) {
					BigDecimal ratio = goods.getLevel1Silver().divide(hundred,2, RoundingMode.HALF_UP);
					_earnings = price.multiply(ratio);

				}else if(distributionFirst.getLevelId() == 3) {
					BigDecimal ratio = goods.getLevel1Gold().divide(hundred,2, RoundingMode.HALF_UP);
					_earnings = price.multiply(ratio);
				}
				if(distributionFirst.getLevelId() == 2 || distributionFirst.getLevelId() == 3) {
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
					logIntegralMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上级代理金币", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得金币"+_earnings.multiply(hundred));
				}
			}

			// 上上级
			if(null != distributionSecond) {
				if(distributionSecond.getLevelId() >= 4) {
					BigDecimal ratio = goods.getLevel2Diamond().divide(hundred,2, RoundingMode.HALF_UP);
					BigDecimal _ratio = goods.getLevel2DiamondGold().divide(hundred,2, RoundingMode.HALF_UP);
					BigDecimal _earnings = price.multiply(ratio);
					BigDecimal _integral = price.multiply(_ratio);
					
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上上级代理余额", "");

					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("integral = integral+"+ _integral.multiply(hundred)));
					logIntegralMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _integral.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");

					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings+",金币"+_integral.multiply(hundred));
				}else {
					BigDecimal _earnings = BigDecimal.ZERO;
					if(distributionSecond.getLevelId() == 2) {
						BigDecimal ratio = goods.getLevel2Silver().divide(hundred,2, RoundingMode.HALF_UP);
						_earnings = price.multiply(ratio);
					}else if(distributionSecond.getLevelId() == 3) {
						BigDecimal ratio = goods.getLevel2Gold().divide(hundred,2, RoundingMode.HALF_UP);
						_earnings = price.multiply(ratio);
					}
					if(distributionSecond.getLevelId() == 2 || distributionSecond.getLevelId() == 3) {
						userMapper.update(null, new UpdateWrapper<User>()
								.eq("id", user.getSecondLeader())
								.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
						logIntegralMapper.add(
								user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");
						eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得金币"+_earnings.multiply(hundred));
					}
				}
			}
		}
	}
    /**
	 * 	计算产品分佣
	 * @param
	 * @param userId
	 */
	private void handleCommission(List<Integer> goodsIds,Integer userId,Order order,User user) {
		List<Goods> goodsList = goodsMapper.selectList(new LambdaQueryWrapper<Goods>().in(Goods::getId, goodsIds));
		if(CollectionUtil.isNotEmpty(goodsList)) {
			Integer userLevel = 1;
			// 修改用户VIP等级
			Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
			if(null != distribution && null != distribution.getExpireTime() && distribution.getExpireTime() > TimeUtils.timestamp()) {
				userLevel = distribution.getLevelId();
			}
			for (Goods goods : goodsList) {
				if(goods.getCommissionType() != 3) {
					// 分佣
					superiorCommission(userId, userLevel, goods, order,user);
				}
			}
		}
	}
	
	/**
	 * 	上级抽佣
	 * @param userId		用户ID
	 * @param userLevel		用户等级
	 * @param goods			商品信息
	 * @param couponListId	优惠总金额
	 * @param user			用户信息
	 */
	public void superiorCommission(Integer userId,Integer userLevel,Goods goods,Order order,User user) {
		if(user.getFirstLeader() <= 0) {
			return;
		}
		Distribution distributionFirst = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getFirstLeader()));
		if(distributionFirst == null) {
			return;
		}else if(distributionFirst.getLevelId() <= 1 || distributionFirst.getExpireTime() < TimeUtils.timestamp()){
			return;
		}
		DistributionLevel distributionLevelFirst = distributionLevelMapper.selectById(distributionFirst.getLevelId());

		DistributionLevel distributionLevelSecond = null;
		Distribution distributionSecond = null;
		if(user.getSecondLeader() > 0) {
			distributionSecond = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getSecondLeader()));
			if(null != distributionSecond && distributionSecond.getLevelId() > 1 && distributionSecond.getExpireTime() > TimeUtils.timestamp()) {
				distributionLevelSecond = distributionLevelMapper.selectById(distributionSecond.getLevelId());
			}
		}
		BigDecimal couponAmount = BigDecimal.ZERO;
		if(null == goods || null == goods.getId()) {
			throw new OperateException("产品有误");
		}
		OrderGoods orderGoods = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId,order.getId()).eq(OrderGoods::getGoodsId, goods.getId())
				.select(OrderGoods::getGoodsPrice));
		if(null == orderGoods || null == orderGoods.getGoodsPrice()) {
			throw new OperateException("产品有误");
		}
		if(StringUtils.isNotEmpty(order.getCouponListId())) {
			if(!"0".equals(order.getCouponListId())){
				BigDecimal _m1 = order.getNeedPayMoney().subtract(order.getExpressMoney());
				BigDecimal _m2 = _m1.divide(order.getGoodsMoney(),2, RoundingMode.HALF_UP);
				BigDecimal _m3 = _m2.multiply(orderGoods.getGoodsPrice());
				couponAmount = orderGoods.getGoodsPrice().subtract(_m3);
			}
		}
		BigDecimal cashbackAmount = BigDecimal.ZERO;
		if(1 == userLevel) {
			cashbackAmount = goods.getCashbackOrdinary();
		}else if(2 == userLevel) {
			cashbackAmount = goods.getCashbackSilver();
		}else if(3 == userLevel) {
			cashbackAmount = goods.getCashbackGold();
		}else if(4 == userLevel) {
			cashbackAmount = goods.getCashbackDiamond();
		}else if(5 == userLevel) {
			cashbackAmount = goods.getCashbackPartner();
		}else if(6 == userLevel) {
			cashbackAmount = goods.getCashbackCreate8();
		}else if(7 == userLevel) {
			cashbackAmount = goods.getCashbackCreate9();
		}
		BigDecimal _c = BigDecimal.ZERO;
		switch (goods.getCommissionType()) {
		case 1:
			// 按利润分佣产品 ： 产品售价-产品供货价-下单再返-领券优惠金额
			_c = orderGoods.getGoodsPrice().subtract(goods.getSupplyPrice()).subtract(cashbackAmount).subtract(couponAmount);
			break;
		case 2:
			// 按售价分佣产品 ： 产品售价-下单再返-领券优惠金额
			_c = orderGoods.getGoodsPrice().subtract(cashbackAmount).subtract(couponAmount);
			break;
		case 3:
			// TODO 月分佣 待沟通
			break;
		}
		if(_c.compareTo(BigDecimal.ZERO) > 0) {
			// 团队会员年费*80%现金 + 所有用户利润1%现金 / 2%
			if(null != distributionLevelFirst.getFirstRatio() && BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionFirst.getLevelId() == 6 || distributionFirst.getLevelId() == 7) {
					BigDecimal _earnings = _c.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上上级团队利润
			if(null != distributionLevelSecond.getFirstRatio() && BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionSecond.getLevelId() == 6 || distributionSecond.getLevelId() == 7) {
					BigDecimal _earnings = _c.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上级 上上级抽佣
			if(distributionFirst.getLevelId() >= 4) { // 钻石以上是余额
				BigDecimal _earnings = BigDecimal.ZERO;
				switch (distributionFirst.getLevelId()) {
				case 4:
					_earnings = goods.getLevel1Diamond();
					break;
				case 5:
					_earnings = goods.getLevel1Partner();
					break;
				case 6:
					_earnings = goods.getLevel1Create8();
					break;
				case 7:
					_earnings = goods.getLevel1Create9();
					break;
				}
				userMapper.update(null, new UpdateWrapper<User>()
						.eq("id", user.getFirstLeader())
						.setSql("earnings = earnings+"+_earnings));
				logEarningsMapper.add(
						user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上级代理余额", "");
				eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
			}else {	// 钻石以下是金币
				BigDecimal _earnings = BigDecimal.ZERO;
				if(distributionFirst.getLevelId() == 2) {
					_earnings = goods.getLevel1Silver();
				}else if(distributionFirst.getLevelId() == 3) {
					_earnings = goods.getLevel1Gold();
				}
				if(distributionFirst.getLevelId() == 2 || distributionFirst.getLevelId() == 3) {
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							//.setSql("earnings = earnings+"+_earnings));
							.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
					logIntegralMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上级代理金币", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得金币"+_earnings.multiply(hundred));
				}
			}
			// 上上级
			if(null != distributionSecond) {
				if(distributionSecond.getLevelId() >= 4) {
					BigDecimal _earnings = BigDecimal.ZERO;
					BigDecimal _integral = BigDecimal.ZERO;
					switch (distributionSecond.getLevelId()) {
					case 4:
						_earnings = goods.getLevel2Diamond();
						_integral = goods.getLevel2DiamondGold();
						break;
					case 5:
						_earnings = goods.getLevel2Partner();
						_integral = goods.getLevel2PartnerGold();
						break;
					case 6:
						_earnings = goods.getLevel2Create8();
						_integral = goods.getLevel2Create8Gold();
						break;
					case 7:
						_earnings = goods.getLevel2Create9();
						_integral = goods.getLevel2Create9Gold();
						break;
					}
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上上级代理余额", "");
					
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("integral = integral+"+ _integral));
					logIntegralMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _integral, goods.getId(), order.getOrderSn(), "上上级代理金币", "");
					
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings+",金币"+_integral);
				}else {
					BigDecimal _earnings = BigDecimal.ZERO;
					if(distributionSecond.getLevelId() == 2) {
						_earnings = goods.getLevel2Silver();
					}else if(distributionSecond.getLevelId() == 3) {
						_earnings = goods.getLevel2Gold();
					}
					if(distributionSecond.getLevelId() == 2 || distributionSecond.getLevelId() == 3) {
						userMapper.update(null, new UpdateWrapper<User>()
								.eq("id", user.getSecondLeader())
								.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
						logIntegralMapper.add(
								user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");
						eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得金币"+_earnings.multiply(hundred));
					}
				}
			}
		}
	}
	
	

    /**
     * 售后时间
     *
     * @author mjf
     * @return Long
     */
    private Long __getAfterSaleDeadline() {
        float afterSalesDay = Float.parseFloat(ConfigUtils.get("trade", "afterSalesDay", "-1"));
        long afterSaleDeadline = TimeUtils.timestamp();
        if (afterSalesDay != -1) {
            afterSaleDeadline = (long)(afterSalesDay *24 * 60 * 60) + TimeUtils.timestamp();
        }
        return afterSaleDeadline;
    }

    /**
	 * 	下单返现
	 * @param goods
	 * @param userId
	 * @param orderSn
	 */
	private void cashback(Goods goods,Integer userId,Order order,BigDecimal price) {
		// 修改用户积分(金币)
		BigDecimal coin = BigDecimal.ZERO;
		if(null != goods.getCashbackRatio() && goods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
			BigDecimal ratio = goods.getCashbackRatio().divide(hundred,2, RoundingMode.HALF_UP);
			coin = price.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
		}
		if(coin.compareTo(BigDecimal.ZERO) > 0) {
			userMapper.update(null, new UpdateWrapper<User>()
					.eq("id", userId)
					.setSql("integral = integral+"+coin.multiply(hundred)));
			logIntegralMapper.add(
					userId, LogMoneyEnum.UI_INC_GOODS.getCode(), coin.multiply(hundred), goods.getId(), order.getOrderSn(),
					"购物返金币", "");
			eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(userId), "本次获得金币"+coin.multiply(hundred));
		}
	}
    /**
     * 判断购买商品之后是否赠送会员
     * @param userId
     * @param order
     * @param orderGoodsList
     */
    @Transactional
    public void receiveVip(Integer userId,Order order,List<OrderGoods> orderGoodsList){

        boolean falg = false;
        List<Integer> levelList = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        Goods goods = new Goods();
        System.out.println("商品"+orderGoodsList.size());
        System.out.println("商品数量"+orderGoodsList.get(0).getGoodsNum());
        //判断商品是否存在赠送会员 并取最高等级会员
        for (OrderGoods orderGoods:orderGoodsList){
            goods = goodsMapper.selectById(orderGoods.getGoodsId());
            if(goods != null){
                //处理多个商品
                for(int i = 0;i<orderGoods.getGoodsNum();i++){
                    goodsList.add(goods);
                }
                if(goods.getReceiveVip() != 0){
                    falg = true;
                    levelList.add(goods.getReceiveVip());
                }
            }
        }
        //获取等级最高的商品数量
        if(falg){
        	Integer level = levelList.stream().max(Integer::compareTo).get();
        	System.out.println("最大的等级："+level);
        	int maxLevelGoods = 0;
        	for(Goods goods1:goodsList){
    			if(goods1.getReceiveVip() == level){
    				maxLevelGoods += 1;
    			}
    		}
        	level = level+1;
            Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
            distribution.setType(2);
            //原等级小于赠送等级则更新
            if(distribution.getLevelId() <= level){
                long currentTimeMillis = System.currentTimeMillis();
                long tenDigitTimestamp = currentTimeMillis / 1000;
                if(distribution.getExpireTime() == null){
                    distribution.setExpireTime(tenDigitTimestamp);
                }
                //如果是同等级就在原有的基础上延长时间 如果升级就重新计算
                if(distribution.getLevelId() == level){
                    Date date = new Date(distribution.getExpireTime() * 1000);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date); // 设置Calendar对象的时间为date
                    calendar.add(Calendar.YEAR, maxLevelGoods);
                    Date newDate = calendar.getTime();
                    distribution.setExpireTime(newDate.getTime() / 1000);
                }else{
                    Date date = new Date(currentTimeMillis);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date); // 设置Calendar对象的时间为date
                    calendar.add(Calendar.YEAR, maxLevelGoods);
                    Date newDate = calendar.getTime();
                    distribution.setExpireTime(newDate.getTime() / 1000);
                }
                distribution.setLevelId(level);
                distributionMapper.updateById(distribution);

                VipRecord model = new VipRecord();
                model.setUserId(userId);
                model.setOrderSn(order.getOrderSn());
                model.setPayWay(0);
                model.setRelatedId(level);
                model.setOrderAmount(order.getPayMoney());
                model.setActualAmount(order.getPayMoney());
                model.setOrderCreateTime(order.getCreateTime());
                model.setOrderUpdateTime(order.getUpdateTime());
                model.setOrderStatus(1);
                model.setExtend(distribution.getExpireTime().toString());
                String remarl = "普通用户";
                switch (level) {
                    case 2:
                        remarl = "开通VIP(银牌会员)";
                        break;
                    case 3:
                        remarl = "开通VIP(金牌会员)";
                        break;
                    case 4:
                        remarl = "开通VIP(钻石会员)";
                        break;
                }
                model.setRemark(remarl);
                vipRecordMapper.insert(model);
            }
        }
    }

}
